package com.webc.framework.start;


import com.webc.framework.bean.RequestHandler;
import com.webc.framework.util.JsonUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import static com.webc.framework.bean.MappingContainer.getRequestHandlerMapping;

/**
 * @author hejianglong
 * @date 2018/9/6.
 */
@WebServlet(urlPatterns = "/",loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, RequestHandler> handlerMapping = getRequestHandlerMapping();
        String requestURI = req.getRequestURI();
        Map<String, String[]> params = req.getParameterMap();
        RequestHandler handler = handlerMapping.get(requestURI);
        if (handler == null) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        String requestMethod = req.getMethod();
        handler.checkMethod(requestMethod);
        Object result = null;
        if(params == null || params.isEmpty()) {
            result = BeanFactory.invokeMethod(handler.getControllerBean(), handler.getMethod());
        } else {
            result = BeanFactory.invokeMethod(handler.getControllerBean(), handler.getMethod(), params);
        }
        handleData(result, resp);
    }

    private void handleData(Object result, HttpServletResponse response) throws IOException {
        if (result == null) {
            return;
        }
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        String json = JsonUtil.toJSON(result);
        writer.write(json);
        writer.flush();
        writer.close();
    }
}
